from PyQt5.QtCore import *
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import *
from UI.show import *
from bitMap import drawMap, readJSON, drawLine
from bokeh.plotting import show
from bokeh.io import export_png
import cv2
import os
import time


class WorkThread(QThread):
    signal_info = pyqtSignal(object)

    def __init__(self, dict_para: dict):
        super().__init__()
        self.dict = dict_para

    def run(self):
        dm = drawMap.DrawMap()
        map_dict = readJSON.ReadJson.get_map_value(self.dict['map_data'])
        res_map = dm.draw_map(map_dict)
        if res_map is None:
            self.signal_info.emit("地图数据内容有误，无法解析！！！")
            return
        if self.dict['show_map']:
            show(res_map)
            # p1 = r'./bokeh_plot.png'  # 图片保存路径
            # option = webdriver.ChromeOptions()
            # option.add_argument('headless')
            # driver = webdriver.Chrome(chrome_options=option)
            # export_png(res_map, filename=p1, width=map_dict.get("width")*3,
            #            height=map_dict.get("height")*3, webdriver=driver)
        else:
            dl = drawLine.DrawLine()
            res_line = dl.drawline(map_dict, res_map,
                                   readJSON.ReadJson.read_path_data(self.dict['history_data']),
                                   'history', len(self.dict['current_data']))
            if len(self.dict['current_data']) != 0:
                res_line = dl.drawline(map_dict, res_map,
                                       readJSON.ReadJson.read_path_data(self.dict['current_data']),
                                       'current', self.dict['current_data'])
            show(res_line)
        # # export_png(res_line, filename="plot.png")
        pass


class MainWindow(QMainWindow):
    # constructor
    def __init__(self, name='Dlg'):
        super().__init__()
        self.label = QLabel()
        self.progressBar = QProgressBar()
        self.ui = Ui_MainWindow()
        self.init_ui(name)

    # init function
    def init_ui(self, name):
        self.ui.setupUi(self)
        self.statusBar().addPermanentWidget(self.label)
        self.statusBar().addPermanentWidget(self.progressBar)
        # This is simply to show the bar
        # self.progressBar.setGeometry(0, 0, 50, 15)
        self.progressBar.setRange(0, 100)  # 设置进度条的范围
        self.progressBar.setValue(0)
        self.setWindowTitle(name)
        self.ui.radioBtn_map_path.setChecked(True)
        self.init_connect()

        # initial slot and connect

    def init_connect(self):
        self.ui.btn_create.clicked.connect(self.create_btn_clicked)
        self.ui.btn_clear.clicked.connect(self.clear_btn_clicked)
        pass

    def create_btn_clicked(self):
        if len(self.ui.textEdit_map.toPlainText()) == 0:
            self.ui.statusbar.setStyleSheet("font-size:15pt;""background-color:#FF0000;")
            self.ui.statusbar.showMessage("地图数据不能为空！！！")
            return
        if self.ui.radioBtn_map_path.isChecked():
            if len(self.ui.textEdit_historypath.toPlainText()) == 0:
                self.ui.statusbar.setStyleSheet("font-size:15pt;""background-color:#FF0000;")
                self.ui.statusbar.showMessage("历史或当前路径不能为空！！！")
                return
        self.ui.statusbar.showMessage("")
        map_data = self.ui.textEdit_map.toPlainText()
        history_data = self.ui.textEdit_historypath.toPlainText()
        current_data = self.ui.textEdit_currentpath.toPlainText()
        is_only_map = False
        if self.ui.radioBtn_map_path.isChecked():
            is_only_map = False
        elif self.ui.radioBtn_only_map.isChecked():
            is_only_map = True

        dict_para = {'map_data': map_data,
                     'history_data': history_data,
                     'current_data': current_data,
                     'show_map': is_only_map}
        self.label.setText("正在生成:")
        # graph = drawMap_pyqtgraph.drawMapGraph()
        # graph.line_plot(self.ui.graphicsView)
        # graph.scatter_plot(self.ui.graphicsView)
        # graph.show_example()
        # graph.three_curves(self.ui.graphicsView)
        self.thread = WorkThread(dict_para)
        self.thread.signal_info.connect(self.update_info)
        self.thread.start()
        # self.show_png()

    @classmethod
    def del_png(cls):
        path = os.getcwd() + "/bokeh_plot.png"
        if os.path.exists(path):
            os.remove(path)
        pass

    @classmethod
    def create_scene(cls):
        cls.del_png()
        path = os.getcwd() + "/bokeh_plot.png"
        if not os.path.exists(path):
            time.sleep(30)
        img = cv2.imread(path)  # 读取图像
        img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)  # 转换图像通道
        x = img.shape[1]  # 获取图像大小
        y = img.shape[0]
        frame = QImage(img.data, x, y, QtGui.QImage.Format_RGB32)
        pix = QPixmap.fromImage(frame)
        item = QGraphicsPixmapItem(pix)  # 创建像素图元
        scene = QGraphicsScene()  # 创建场景
        scene.addItem(item)
        return scene

    def show_png(self):
        self.ui.graphicsView.setScene(self.create_scene())
        # self.ui.graphicsView.fitInView(item, Qt.IgnoreAspectRatio)  # 自适应view

    def clear_btn_clicked(self):
        self.ui.textEdit_map.setText("")
        self.ui.textEdit_historypath.setText("")
        self.ui.textEdit_currentpath.setText("")
        self.ui.graphicsView
        pass

    def update_info(self, str_info):
        self.ui.statusbar.showMessage(str_info)
